from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from google.appengine.api import users
import json as simplejson
from models.HangHoa import HangHoa
from utils.permission_required import permission_required
import WSGI
import logging
import math
import webapp2

logger = logging.getLogger("GUIQuanLyNhanVien")

class GuiQuanLyHangHoa(webapp2.RequestHandler):
    priv = ''
    perm = 'HangHoa.QuanLyHangHoa'
    @permission_required
    def get(self):
        lstHangHoa = DaoQuanLyNhanVien.getAllHangHoa()
        for item in lstHangHoa:
            item['tenHangHoa'] = str(item['id']) + ' - ' + item['tenHangHoa']
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'lstHangHoa': lstHangHoa,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/QuanLyHangHoa.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListHangHoa': 'getListHangHoa',
                       'updateHangHoa': 'updateHangHoa'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListHangHoa(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maHangHoa = self.request.get('maHangHoa')
        rows, rowNum = DaoQuanLyNhanVien.getListHangHoa(maHangHoa, gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateHangHoa(self):
        maHangHoa = self.request.get('id')
        if maHangHoa != '_empty':
            hh = HangHoa.get_by_id(int(maHangHoa))
            if hh.tenHangHoa != self.request.get('tenHangHoa'):
                DaoQuanLyNhanVien.updateTenHangHoa(maHangHoa, self.request.get('tenHangHoa'))
        else:
            hh = HangHoa()
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            DaoQuanLyNhanVien.deleteHangHoa(hh)
            return 1
        else:
            hh.tenHangHoa = self.request.get('tenHangHoa')
            hh.giaMacDinh = float(self.request.get('giaMacDinh'))
            if self.request.get('soLuongTonKho') != '':
                hh.soLuongTonKho = float(self.request.get('soLuongTonKho'))
            
            DaoQuanLyNhanVien.createOrUpdateHangHoa(hh)
            return 1
        
        
            
        